// pages/saveBabaPage/saveBabaPage.js
const dataType = require('../../data/data.js')
const db = wx.cloud.database()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startTime: '',
    state: app.globalData.state,//0表示没开始拉粑粑，1表示正在拉粑粑，2表示结束拉粑粑
    displayTime: '00分00秒',
    minutes: 0,
    seconds: 0,
    totalTime: 0,
    timer: '',
    babaImage: dataType.babaImages,
    babaShape: dataType.babaShape,
    babaColor: '(褐色)',
    babaText: `(${dataType.babaShape[0].text})`,
    babaHerf: dataType.babaHeft,
    herf: `(${dataType.babaHeft[0].heft})`,
    totalBaba: 0,
    weekDay: ''
  },

  init() {
    this.setData({
      startTime: '',
      displayTime: '00分00秒',
      minutes: 0,
      seconds: 0,
      totalTime: 0,
      timer: '',
    })
  },

  babaColor(e) {
    const index = e.currentTarget.dataset.index
    const updataImage = this.data.babaImage.map((item, idx) => {
      if (idx === index) {
        const color = `(${item.color})`
        this.setData({
          babaColor: color
        })
        return { ...item, isSelect: true }; // 将点击的日期设为选中
      } else {
        return { ...item, isSelect: false }; // 其他日期设为未选中
      }

    })
    this.setData({
      babaImage: updataImage
    })
  },


  babaShape(e) {
    const index = e.currentTarget.dataset.shape
    const updataShape = this.data.babaShape.map((item, idx) => {
      if (idx === index) {
        const shapeText = `(${item.text})`
        this.setData({
          babaText: shapeText
        })
        return ({ ...item, isSelect: true })
      } else {
        return ({ ...item, isSelect: false })
      }
    })
    this.setData({
      babaShape: updataShape
    })
  },

  babaHeft(e) {
    const index = e.currentTarget.dataset.heft
    const updataHeft = this.data.babaHerf.map((item, idx) => {
      if (idx === index) {
        const heft = `(${item.heft})`
        this.setData({
          herf: heft
        })
        return ({ ...item, isSelect: true })
      } else {
        return ({ ...item, isSelect: false })
      }
    })
    this.setData({
      babaHerf: updataHeft
    })
  },

  update() {
    const updataImage = this.data.babaImage.map((item, idx) => {
      if (idx === 0) {
        return { ...item, isSelect: true }; // 将点击的日期设为选中
      } else {
        return { ...item, isSelect: false }; // 其他日期设为未选中
      }
    })

    const updataShape = this.data.babaShape.map((item, idx) => {
      if (idx === 0) {
        return ({ ...item, isSelect: true })
      } else {
        return ({ ...item, isSelect: false })
      }
    })

    const updataHeft = this.data.babaHerf.map((item, idx) => {
      if (idx === 0) {
        return ({ ...item, isSelect: true })
      } else {
        return ({ ...item, isSelect: false })
      }
    })
    this.setData({
      babaImage: updataImage,
      babaShape: updataShape,
      babaHerf: updataHeft
    })
  },

  cancelBaba() {
    app.globalData.state = 0
    wx.navigateBack()
  },

  async updateUserInfo() {
    const res = await wx.cloud.callFunction({
      name: 'inquireUserInfo'
    })
    console.log(res)
    const dbResult = await wx.cloud.callFunction({
      name: 'inquireDatabase'
    })
    console.log(dbResult, dbResult.result.data.length)
    let total = 0
    dbResult.result.data.forEach(item => {
      total = total + Number(item.totalBaba)
    })
    db.collection('user').doc(res.result.data[0]._id).update({
      data: {
        babaMinutes: total,
        babaTimes: dbResult.result.data.length
      },
      success: function (res) {
        console.log(res)
      }
    })
    const user = res.result.data[0]
    const record = {
      _id: user._id,
      avaterUrl: user.avaterUrl,
      babaTimes: dbResult.result.data.length,
      babaMinutes: total,
      userName: user.userName,
      _openid: user._openid
    }
    try {
      const userInfoCache = wx.getStorageSync('userInfoResult') || {}
      const existingIndex = userInfoCache.data.findIndex(item => item._id === record._id);
      if (existingIndex == -1) {
        userInfoCache.data.push(record);
      } else {
        userInfoCache.data[existingIndex] = record;
      }
      wx.setStorageSync('userInfoResult', userInfoCache);
      console.log('缓存保存成功')
    } catch (e) {
      console.error('缓存保存失败:', e)
    }

  },

  saveBaba() {
    const updateColor = this.data.babaImage.filter(item => item.isSelect);
    const updateShape = this.data.babaShape.filter(item => item.isSelect);
    const updateHeft = this.data.babaHerf.filter(item => item.isSelect);
    const record = {
      startTime: this.data.startTime,
      displayTime: this.data.displayTime,
      babaColor: updateColor[0].color,
      babaShape: updateShape[0].shape,
      babaHeft: updateHeft[0].heft,
      totalBaba: this.data.totalBaba,
      weekDay: this.data.weekDay
    };
    db.collection('baba').add({
      data: record,
      success: async () => {
        try {
          const cacheResult = wx.getStorageSync('dataBaseResult') || {};
          cacheResult.data.push(record);
          wx.setStorageSync('dataBaseResult', cacheResult);
          console.log('缓存保存成功');
        } catch (error) {
          console.error('缓存保存失败:', error);
        }
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1000,
        });
        this.update();
        this.updateUserInfo();
        wx.navigateBack();
        app.globalData.state = 0;
        this.setData({
          state: app.globalData.state
        });
        this.init();
      },
      fail: () => {
        wx.showToast({
          title: '保存失败',
          icon: 'error'
        });
      }
    });



  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      startTime: options.startTime,
      displayTime: options.displayTime,
      totalBaba: options.totalBaba,
      weekDay: options.weekDay
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})